package com.zjh.document.controller;

import com.zjh.document.service.impl.MinIOService;
import com.zjh.document.service.impl.MinioUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/documentManager/wangEditor")
public class WangEidtorController {

    @Autowired
    MinIOService minIOService;
    @Value("${file.upload.folder:upload-files}")
    private String fileUploadFolder;
    @Value("${server.protocol:http}")
    private String protocol;
    @Value("${server.ip:localhost}")
    private String ip;
    @Value("${server.port:8080}")
    private String port;

    @Value("${minio.bucket}")
    private String bucket;
    @Resource
    private MinioUtils minioUtils;

    @PostMapping
    public ResponseEntity<?> saveFiles(MultipartHttpServletRequest request, @RequestParam(value = "path") String path) {

        List<FileUploadResponse> fileResponses = new ArrayList<>();


        // Process each file
        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            String name = fileNames.next();
            MultipartFile file = request.getFile(name);

            if (file != null && !file.isEmpty()) {
                String originalFileName = file.getOriginalFilename();
                String randomFileName = generateRandomFileName(originalFileName);
                String finalFilePath = path + randomFileName;
                log.info(path);
                log.info(finalFilePath);
                boolean res = minIOService.uploadFile(bucket, file, finalFilePath);

                if (res) {
                    String url = minioUtils.getPresignedObjectUrl(bucket, finalFilePath);

                    fileResponses.add(new FileUploadResponse(url, finalFilePath, url));
                }

            }
        }

        // Return appropriate response based on number of files
        if (fileResponses.isEmpty()) {
            return ResponseEntity.badRequest().body(
                    new ErrorResponse(1, "No files were uploaded"));
        } else {
            return ResponseEntity.ok(new SuccessResponse(
                    0,
                    fileResponses.size() == 1 ? fileResponses.get(0) : fileResponses));
        }

    }

    private String generateRandomFileName(String originalFileName) {
        if (originalFileName == null || originalFileName.isEmpty()) {
            return UUID.randomUUID().toString().substring(0, 8);
        }

        int lastDotIndex = originalFileName.lastIndexOf('.');
        if (lastDotIndex < 0) {
            return originalFileName + "-" + getRandomSuffix();
        }

        String nameWithoutExt = originalFileName.substring(0, lastDotIndex);
        String extension = originalFileName.substring(lastDotIndex + 1);
        return nameWithoutExt + "-" + getRandomSuffix() + "." + extension;
    }

    private String getRandomSuffix() {
        return UUID.randomUUID().toString().substring(0, 6);
    }

    // Response classes
    private static class SuccessResponse {
        private int errno;
        private Object data;

        public SuccessResponse(int errno, Object data) {
            this.errno = errno;
            this.data = data;
        }

        public int getErrno() {
            return errno;
        }

        public Object getData() {
            return data;
        }
    }

    private static class ErrorResponse {
        private int errno;
        private String message;

        public ErrorResponse(int errno, String message) {
            this.errno = errno;
            this.message = message;
        }

        public int getErrno() {
            return errno;
        }

        public String getMessage() {
            return message;
        }
    }

    private static class FileUploadResponse {
        private String url;
        private String alt;
        private String href;

        public FileUploadResponse(String url, String alt, String href) {
            this.url = url;
            this.alt = alt;
            this.href = href;
        }

        public String getUrl() {
            return url;
        }

        public String getAlt() {
            return alt;
        }

        public String getHref() {
            return href;
        }
    }
}